package com.apesource.project02.service;

import com.alibaba.fastjson.JSON;
import com.apesource.project02.mapper.IMessagesMapper;
import com.apesource.project02.mapper.IRegistrationsMapper;
import com.apesource.project02.mapper.IResultsMapper;
import com.apesource.project02.mapper.IUserMapper;
import com.apesource.project02.pojo.Message;
import com.apesource.project02.pojo.Registration;
import com.apesource.project02.pojo.Result;
import com.apesource.project02.pojo.User;
import com.apesource.project02.util.ResponseEntity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @auther:暮雪
 * @date:2025/9/18
 */

@Service
public class UserServiceImp extends ServiceImpl<IUserMapper, User> implements IUserServer {
    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private IRegistrationsMapper registrationsMapper;

    @Autowired
    private IMessagesMapper messagesMapper;

    @Autowired
    private IResultsMapper resultsMapper;

    @Autowired
    private RedisTemplate jsonRedisTemplate;

    @Override
    public ResponseEntity<User> registerUser(User user) {
        user.setRegistrationTime(new Date());
        ResponseEntity<User> responseEntity = new ResponseEntity<>();
        int result = userMapper.insert(user);
        if (result >= 1) {
            jsonRedisTemplate.opsForValue().set("user:id:" + user.getUserId(), JSON.toJSONString(user));
        }
        responseEntity.setStatusCode(201);
        responseEntity.setData(user);
        responseEntity.setMessage("success");
        return responseEntity;
    }

    @Override
    public ResponseEntity<User> findUserById(int userId) {
        ResponseEntity<User> responseEntity = new ResponseEntity<>();
        User user;
        Object object = jsonRedisTemplate.opsForValue().get("user:id:" + userId);
        if (object == null) {
            user = userMapper.selectById(userId);
            if (user != null) {
                jsonRedisTemplate.opsForValue().set("user:id:" + userId, JSON.toJSONString(user));
            }
        } else user = JSON.parseObject(object.toString(), User.class);
        if (user != null) {
            responseEntity.setStatusCode(200);
            responseEntity.setData(user);
            responseEntity.setMessage("success");
        } else {
            responseEntity.setStatusCode(404);
            responseEntity.setMessage("not found");
        }
        return responseEntity;
    }


    @Override
    public ResponseEntity<User> updateUser(User user) {
        ResponseEntity<User> responseEntity = new ResponseEntity<>();
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserId, user.getUserId());
        int res = userMapper.update(user, lambdaQueryWrapper);
        if (res > 0) {
            jsonRedisTemplate.opsForValue().set("user:id:" + user.getUserId(), JSON.toJSONString(user));
            responseEntity.setStatusCode(200);
            responseEntity.setData(user);
            responseEntity.setMessage("success");
        } else {
            responseEntity.setStatusCode(404);
            responseEntity.setMessage("not found");
        }
        return responseEntity;
    }


    @Override

    public ResponseEntity<User> deleteUser(int userId) {
        ResponseEntity<User> responseEntity = new ResponseEntity<>();
        LambdaQueryWrapper<Registration> registrationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        registrationLambdaQueryWrapper.eq(Registration::getUserId, userId);
        List<Registration> registrationList = registrationsMapper.selectList(registrationLambdaQueryWrapper);
        int count = 0;
        if (registrationList.size() == 0) {
            LambdaQueryWrapper<Result> lambdaQueryWrapperResult = new LambdaQueryWrapper<>();
            lambdaQueryWrapperResult.eq(Result::getUserId, userId);
            List<Result> resultList = resultsMapper.selectList(lambdaQueryWrapperResult);
            if (resultList.size() != 0) {
                for (Result result : resultList) {
                    resultsMapper.deleteById(result.getResultId());
                    jsonRedisTemplate.delete("result:id:" + result.getResultId());
                }
            }
            userMapper.deleteById(userId);
            jsonRedisTemplate.delete("user:id:" + userId);
        } else {
            count = registrationList.size();
            for (Registration registration : registrationList) {
                if (registration.getStatus().equals("已完赛")) {
                    LambdaQueryWrapper<Result> lambdaQueryWrapperResult1 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapperResult1.eq(Result::getUserId, userId).eq(Result::getEventId, registration.getEventId());
                    List<Result> resultList = resultsMapper.selectList(lambdaQueryWrapperResult1);
                    if (resultList.size() != 0) {
                        for (Result result : resultList) {
                            resultsMapper.deleteById(result.getResultId());
                            jsonRedisTemplate.delete("result:id:" + result.getResultId());
                        }
                    }
                    registrationsMapper.deleteById(registration.getRegistrationId());
                    jsonRedisTemplate.delete("registration:id:" + registration.getRegistrationId());
                    count -= 1;
                }
            }
            LambdaQueryWrapper<Message> lambdaQueryWrapperMessage = new LambdaQueryWrapper<>();
            lambdaQueryWrapperMessage.eq(Message::getUserId, userId);
            List<Message> messageList = messagesMapper.selectList(lambdaQueryWrapperMessage);
            if (messageList.size() != 0) {
                for (Message message : messageList) {
                    messagesMapper.deleteById(message.getMessageId());
                    jsonRedisTemplate.delete("message:id:" + message.getMessageId());
                }
            }
        }
        if (count == 0) {
            responseEntity.setStatusCode(204);
            responseEntity.setMessage("success");
        } else if (count != registrationList.size()) {
            responseEntity.setStatusCode(205);
            responseEntity.setMessage("partial deletion");
        } else {
            responseEntity.setStatusCode(409);
            responseEntity.setMessage("delete failed");
        }
        return responseEntity;
}
}
